package com.vincent.file.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author vincent
 * @date 2020/1/3
 * @description
 * 测试文件上传功能，其中文件上传大小限制在application.yaml中有对应配置
 * 此处演示直接从MultipartFile获取流，可以将此流直接写入ftp服务器中，避免文件落地的情况
 */
@RestController
@RequestMapping("file")
@Slf4j
public class FileController {

    @PostMapping("/upload")
    public String upload(@RequestParam String fileName, MultipartFile file) {

        try (InputStream inputStream = file.getInputStream();
             FileOutputStream bos = new FileOutputStream("D:\\JavaCode\\file\\"+fileName)
        ) {
            log.info("fileName={}", file.getOriginalFilename());
            byte[] buffer = new byte[1024];
            int size;
            while ((size = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, size);
                bos.flush();
            }
            log.info("file {} write finished", fileName);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return "error";
        }
        return "ok";
    }
}
